package com.example.supermarket.controller;

import com.example.supermarket.entity.*;
import com.example.supermarket.entity.dto.FlowDTO;
import com.example.supermarket.entity.dto.IndentDTO;
import com.example.supermarket.entity.dto.OrderDTO;
import com.example.supermarket.entity.vo.IndentVO;
import com.example.supermarket.mapper.IndentMapper;
import com.example.supermarket.service.IndentService;
import com.example.supermarket.util.ExcelIndentView;
import com.example.supermarket.util.MyUtil;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/indent")
public class IndentController {
    @Autowired
    IndentService indentService;
    @Autowired
    IndentMapper indentMapper;
    @Autowired
    MyUtil myUtil;

    @ResponseBody//带条件查询所有信息
    @PostMapping("/get/{pageIndex}/{pageSize}")
    public ResponseResult<PageBean<IndentVO>> getAllIndent(
            @PathVariable("pageIndex") int pageIndex,
            @PathVariable("pageSize") int pageSize,
            @RequestBody IndentDTO indentDTO){
        System.out.println(indentDTO);
        return new ResponseResult<PageBean<IndentVO>>(200,"success",
                indentService.getAllIndent(pageIndex,pageSize,indentDTO));
    }

    @ResponseBody
    @GetMapping("/sendWay/all")//查询所有的送货方式
    public ResponseResult<List<SendWay>> getAllSendWay(){
        List<SendWay> li = indentService.getAllSendWay();
        return new ResponseResult<List<SendWay>>(200,"success",li);
    }

    @ResponseBody
    @GetMapping("/kind/all")//查询所有的商品种类
    public ResponseResult<List<Kind>> getAllKind(){
        List<Kind> li = indentService.getAllKind();
        return new ResponseResult<List<Kind>>(200,"success",li);
    }

    @RequestMapping("/getAllProductName/{zlId}")//根据商品种类获取商品名
    public ResponseResult<List<Product>> getAllProductNameByZlId(@PathVariable ("zlId") Integer zlId){
        log.info("种类Id={}",zlId);
        List<Product> list = indentService.getAllProductNameByZlId(zlId);
        return new ResponseResult<List<Product>>(200,"success",list);
    }

    @RequestMapping("/getPriceByName/{spId}")//根据商品名获取价格信息
    public ResponseResult<Double> getPriceByProductName(@PathVariable ("spId") Integer spId){
        log.info("商品Id={}",spId);
        double spPrice = indentService.getPriceByProductName(spId);
        return new ResponseResult<Double>(200,"success",spPrice);
    }

    @RequestMapping("/payMoney/{ddId}")//商品支付
    public ResponseResult payMoney(@PathVariable ("ddId") String ddId){
        log.info("订单Id={}",ddId,"商品支付");
        String type = "付款成功";
        indentService.changeDdStatus(ddId,type);
        //将付款时间写入数据库
        String time = myUtil.getTimeNow();
        indentService.addNewFkDate(ddId, time);
        return new ResponseResult(200,"success",null);
    }

    @RequestMapping("/deliverGoods/{ddId}")//商品出库
    public ResponseResult deliverGoods(@PathVariable ("ddId") String ddId){
        log.info("订单Id={}",ddId,"商品出库");
        String type = "商品出库";
        //修改订单状态
        indentService.changeDdStatus(ddId, type);
        //将订单处理时间写入数据库
        String time = myUtil.getTimeNow();
        indentService.addNewFhDate(ddId, time);
        return new ResponseResult(200,"success",null);
    }

    @RequestMapping("/recivePackage/{ddId}")//确认收货
    public ResponseResult recivePackage(@PathVariable ("ddId") String ddId){
        log.info("订单Id={}",ddId,"确认收货");
        String type = "确认收货";
        //修改订单状态
        indentService.changeDdStatus(ddId, type);
        //将订单处理时间写入数据库
        String time = myUtil.getTimeNow();
        indentService.addNewShDate(ddId, time);
        return new ResponseResult(200,"success",null);
    }

    @RequestMapping("/finishIndent/{ddId}")//确认交易完成
    public ResponseResult finishIndentByDdId(@PathVariable ("ddId") String ddId){
        log.info("订单Id={}",ddId,"交易完成");
        //修改订单状态
        indentService.finishIndentByDdId(ddId);
        //将订单处理时间写入数据库
        String time = myUtil.getTimeNow();
        indentService.addNewWcDate(ddId, time);
        return new ResponseResult<>(200,"success",null);
    }

    @RequestMapping("/addNewOrder")//添加新的订单
    public ResponseResult<Boolean> addNewOrder(@RequestBody OrderDTO orderDTO, BindingResult bindingResult) {
        log.info("订单信息={}", orderDTO);
        //后端验证
        Map<String, String> errors = new HashMap<>();
        if (bindingResult.getFieldErrorCount() > 0) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                errors.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            bindingResult.getFieldErrors().forEach(item -> errors.put(item.getField(), item.getDefaultMessage()));
            return new ResponseResult(400, "valid error", errors);
        } else {
            //自动生成数据
            orderDTO = addNewData(orderDTO);
            //判断用户信息是否存在
            boolean flag = indentService.selectCustomer(orderDTO.getName(), orderDTO.getPhone());
            if(flag){
                //如果用户存在就不添加到用户表
                indentService.addNewOrder(orderDTO);
                //去查找这个用户的id
                Integer gkId = indentMapper.selectCustomer(orderDTO.getName(),orderDTO.getPhone());
                //将消费者id放到订单表里
                indentService.insertNewGkId(orderDTO.getDdId(),gkId);

                //生成售后单号
                String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 9);
                String str = "T20"+uuid;
                String time = myUtil.getTimeNow();
                //将下单时间存入aftersale表里
                indentService.addNewAfterSale(str, orderDTO.getDdId(), time);
            }else{
                //用户不存在，两个表都添加
                indentService.addNewOrder(orderDTO);
                //添加信息到用户表
                Integer gkId = indentService.addNewCustomer(orderDTO);
                //将新增的消费者id放到订单表里
                indentService.insertNewGkId(orderDTO.getDdId(),gkId);

                //生成售后单号
                String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 9);
                String str = "T20"+uuid;
                String time = myUtil.getTimeNow();
                //将下单时间存入aftersale表里
                indentService.addNewAfterSale(str, orderDTO.getDdId(), time);
            }
            return new ResponseResult<Boolean>(200, "success", null);
        }
    }

    //自动生成一些数据
    public OrderDTO addNewData(OrderDTO orderDTO){
        // 获取当前日期
        Date currentDate = new Date(System.currentTimeMillis());
        // 使用 Calendar 类增加一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        // 获取增加一天后的日期
        Date nextDate = new Date(calendar.getTimeInMillis());
        // 将日期转换为指定格式的字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(nextDate);
        System.out.println(formattedDate);

        //下单时间，yyyy-MM-dd
        orderDTO.setDdOrdertime(new java.sql.Date(new Date().getTime()).toString());
        //如果是自提那么就不需要更改发货时间，如果不是则将发货时间设置为下单的后一天
        if(orderDTO.getDelivertime().equals("")){
            orderDTO.setDelivertime(formattedDate);
        }
        //订单号
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 17);
        String str = "T20"+uuid;
        orderDTO.setDdId(str);
        //下单支付状态
        if(orderDTO.getPayWay()!=""){
            orderDTO.setDdPaystatus("已支付");
            orderDTO.setDdStatus("付款成功");
            orderDTO.setDdType("进行中");
        }else{
            orderDTO.setPayWay("微信");
            orderDTO.setDdPaystatus("未支付");
            orderDTO.setDdStatus("买家下单");
            orderDTO.setDdType("未开始");
        }

        orderDTO.setEmail("123@qq.com");
        orderDTO.setBirthday("2001-01-07");

        return orderDTO;
    }

    @PostMapping("/delete/{ddId}")//根据订单id删除信息
    public Object deleteByDdId(@PathVariable String ddId){
        indentService.deleteByDdId(ddId);
        return new ResponseResult<>(200,"success",null);
    }

    @RequestMapping("/removeBatch")//批量删除后端判断是否删除
    public ResponseResult<Void> removeIndentBatch(@RequestBody String[] ids){
        log.info("批量删除={}", Arrays.toString(ids));
        //判断订单状态是否为进行中，有一个则取消删除
        boolean flag = indentService.removeIndentBatch(ids);
        if(flag){
            return new ResponseResult<Void>(200,"success",null);
        }else{
            return new ResponseResult<Void>(400,"failed",null);
        }

    }

    @RequestMapping("/modifyFlow")//修改收货信息
    public ResponseResult modifyFlowInfo(@RequestBody FlowDTO flowDTO){
        log.info("收货信息={}",flowDTO);
        //先通过订单Id找到顾客Id
        int id = indentService.getCustomerIdByDdId(flowDTO.getOrderId());
        flowDTO.setId(id);
        indentService.modifyFlowInfo(flowDTO);//再修改信息
        indentService.modifyFlowInfo1(flowDTO);
        return new ResponseResult(200,"success",null);
    }


    @GetMapping("/export/{pageIndex}/{pageSize}")//导出
    public ModelAndView export(@PathVariable("pageIndex") int pageIndex,
                         @PathVariable("pageSize")  int pageSize,
                         @RequestParam(required = false) IndentDTO indentDTO, Map map){
        ModelAndView modelAndView = new ModelAndView(new ExcelIndentView());
        PageHelper.startPage(pageIndex,pageSize);
        List<IndentVO> indents = indentMapper.getAllIndent(indentDTO);
        modelAndView.addObject("indents", indents); // 添加需要导出的数据
        map.put("indents",indents);
        return modelAndView;
    }


    /*@Value("${example.file-path}")
    String path;
    @PostMapping("/img/{spImage}")
    @ResponseBody
    public ResponseResult<String> uploadImage(@PathVariable("spImage") String spImage){

        String str = "file:" + path + spImage;
        //           file:///D:/temp/1692974165625
        return new ResponseResult<>(200,"success",str);
    }*/

}

